<template>
  <div class="permission">
    <el-card>
      <div class="btn">
        <el-button
          type="primary"
          size="mini"
          @click="add(1, 0)"
        >添加菜单</el-button>
      </div>
      <el-table :data="tableData" row-key="id" border>
        <el-table-column prop="name" label="菜单名称" sortable width="180" />
        <el-table-column prop="code" label="权限标识" sortable width="180" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button type="text" @click="add(2, row.id)" v-if='row.type===1'>添加权限</el-button>
            <el-button type="text">查看api权限</el-button>
            <el-button type="text" @click="openEdit(row.id)">查看</el-button>
            <el-button type="text" @click="del(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <aded
      ref="aded"
      :show-aded.sync="showAded"
      @updateAded="getAllPermission"
    />
  </div>
</template>

<script>
import { getAllPermissionApi, delSysPermissionApi } from '@/api/permission'
import aded from './componments/aded.vue'
export default {
  components: {
    aded
  },
  data() {
    return {
      tableData: [],
      showAded: false
    }
  },
  created() {
    this.getAllPermission()
  },
  methods: {
    add(type, pid) {
      this.showAded = true
      this.$refs.aded.setProp(type, pid)
    },
    async getAllPermission() {
      const res = await getAllPermissionApi()
      // console.log(res)
      const data = this.turnData(res, '0')
      // console.log(data)
      this.tableData = data
    },
    openEdit(id) {
      this.showAded = true
      this.$refs.aded.getSysPermissionApi(id)
    },

    async del(id) {
      try {
        await this.$confirm('是否要删除当前权限', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        })
        await delSysPermissionApi(id)
        this.$message.success('删除成功')
        this.getAllPermission()
      } catch {
        this.$message.error('取消删除')
      }
    },
    turnData(arr, str) {
      // const newarr = []
      // arr.forEach(item => {
      //   if (item.pid === str) {
      //     const children = this.turnData(arr, item.id)
      //     if (children.length > 0) {
      //       item.children = children
      //     }
      //     newarr.push(item)
      //   }
      // })
      // return newarr
      // 方式二
      const res = arr.filter(item => {
        if (item.pid === str) {
          const children = this.turnData(arr, item.id)
          if (children.length > 0) {
            item.children = children
          }

          return true
        }
        return false
      })
      return res
      // console.log(res)
    }
  }
}
</script>

<style lang="scss" scoped>
.permission {
  padding: 20px;
  .btn {
    text-align: right;
  }
}
</style>
